<script lang="ts" setup>
import { computed, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { Button, Divider, message, Space } from 'ant-design-vue'

import { useVbenForm } from '#/adapter/form'
import { adminAdd, adminUpdata, getAdminInfo, getGroupList } from '#/api/admin'
import { AdminGoodsCategory } from '#/api/spuBom'
import { upload_file_qiniu } from '#/api/upload'

const emit = defineEmits(['refresh'])
const GoodsCategory = ref<any>([])
const groupArr = ref<any>([])

const idsArr: any = ref([])
const inputDisabled = ref(true)

const Text: any = computed(() => {
  return idsArr.value.length > 1 ? '保存并编辑下一项' : '保存'
})
const passwordRules = computed(() => (inputDisabled.value ? undefined : 'required'))
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-4/5',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'CustomRender',
      fieldName: '_divider',
      formItemClass: 'col-span-3',
      hideLabel: true,
    },
    {
      component: 'Upload',
      componentProps: {
        accept: '.png,.jpg,.jpeg',
        customRequest: upload_file_qiniu,
        disabled: false,
        maxCount: 1,
        multiple: false,
        showUploadList: true,
        listType: 'picture-card',
      },
      fieldName: 'avatar',
      label: '头像',
      formItemClass: 'col-span-3',
      renderComponentContent: () => {
        return {
          default: () => '点击上传',
        }
      },
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '用户名',
      },
      fieldName: 'username',
      label: '用户名',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '昵称',
      },
      fieldName: 'nickname',
      label: '昵称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '真实姓名',
      },
      fieldName: 'realname',
      label: '真实姓名',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '',
      },
      fieldName: 'mobile',
      label: '手机号',
      rules: 'required',

    },
    {
      component: 'InputPassword',
      componentProps: {
        visibilityToggle: false,
      },
      fieldName: 'password',
      label: '密码',
      defaultValue: '123456',
      rules: passwordRules,
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '微信unionid',
      },
      fieldName: 'wx_unionid',
      label: '微信unionid',
      formItemClass: 'col-start-1',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '公众号openid',
      },
      fieldName: 'wx_openid',
      label: '公众号openid',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '小程序openid',
      },
      fieldName: 'wx_mini_openid',
      label: '小程序openid',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: GoodsCategory,
        showSearch: true,
        mode: 'multiple',
      },
      fieldName: 'category',
      formItemClass: 'col-span-3',
      label: '类目',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: groupArr,
        showSearch: true,
        fieldNames: {
          label: 'label',
          value: 'value',
          children: 'children',
        },
        mode: 'multiple',
      },
      fieldName: 'group_arr',
      formItemClass: 'col-span-3',
      rules: 'required',
      label: '分组',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        placeholder: '',
      },
      fieldName: 'motto',
      formItemClass: 'col-span-3',
      label: '个性签名',
    },
    {
      component: 'Switch',
      fieldName: 'status',
      label: '状态',
      defaultValue: '1',
      componentProps: {
        class: 'w-[50px]',
        checkedValue: '1',
        unCheckedValue: '0',
      },
    },
  ],
  wrapperClass: 'grid-cols-3',
})

const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  class: 'w-[50%] h-[100%]',
  appendToMain: true,
  fullscreenButton: false,
  onCancel() {
    modalApi.close()
    emit('refresh')
  },
  onConfirm: async () => {
    await baseFormApi.validateAndSubmitForm()
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { rowData, view } = modalApi.getData<Record<string, any>>()
      const parmas = {
        is_select: true,
        page: 1,
        initKey: 'id',
        select: true,
      }
      AdminGoodsCategory(parmas).then((res: any) => {
        GoodsCategory.value = res.list.map((item) => ({
          label: item.name,
          value: item.id,
        }))
      })

      const parmas1 = {
        isTree: true,
        page: 1,
        absoluteAuth: 1,
        initKey: 'id',
        select: true,
      }
      getGroupList(parmas1).then((res: any) => {
        groupArr.value = res.options.map((item) => ({
          label: item.name,
          value: item.id,
        }))
      })

      if (view === 'add') {
        inputDisabled.value = false
      } else if (view === 'edit') {
        if (Array.isArray(rowData)) {
          // 如果是多个编辑
          idsArr.value = rowData
          initData(rowData[0])
        } else {
          inputDisabled.value = true
          initData(rowData)
        }
      }
    }
  },
})

async function initData(rowData: any) {
  getAdminInfo({ id: rowData }).then(async (response) => {
    const row = response.row
    row.avatar = [
      {
        url: row.avatar,
        name: row.avatar,
        uid: row.avatar,
        status: 'success',
      },
    ]
    console.log(row)
    await baseFormApi.setValues(row, false)
  })
}

// 保存
async function save() {
  const { valid } = await baseFormApi.validate()
  if (!valid) {
    return
  }
  const values = await baseFormApi.getValues()
  if (values.avatar && values.avatar.length > 0) {
    const imgs = values.avatar.map((item: any) => {
      let imgPath = item.url ? item.url : (item.response ?? '')
      // 剔除环境变量前缀，只保存相对路径
      if (imgPath.startsWith('http://yyq.babiboy.com')) {
        imgPath = imgPath.replace('http://yyq.babiboy.com', '')
      }
      return imgPath
    })
    values.avatar = imgs[0]
  }
  console.log(values)
  const parmas = {
    ...values,
  }
  if (values.id) {
    // 如果是多个编辑
    if (idsArr.value.length > 1) {
      adminUpdata(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          const index = idsArr.value.indexOf(values.id)
          // 如果找到了对应的值，使用 splice 删除它
          if (index !== -1) {
            idsArr.value.splice(index, 1)
            initData(idsArr.value[0])
          }
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    } else {
      adminUpdata(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          modalApi.close()
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    }
  } else {
    adminAdd(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  }
}
</script>

<template>
  <Modal :title="inputDisabled ? '编辑' : '新建'">
    <BaseForm>
      <template #_divider>
        <Divider orientation="left">基础信息</Divider>
      </template>
    </BaseForm>
    <template #footer>
      <div class="flex justify-end">
        <Space>
          <Button @click="modalApi.close()">取消</Button>
          <Button type="primary" @click="save()">{{ Text }}</Button>
        </Space>
      </div>
    </template>
  </Modal>
</template>

<style scoped>
.fina-box {
  padding: 10px 0;
}
.fina-btn {
  margin-bottom: 16px;
}
</style>
